﻿using System;
using DimensionsHelper.Common.Contracts.Excel;

namespace DimensionsHelper.Services.DataCollector;

public class ExcelData
{
    private ExcelDataValue[]? _dataArray;

    public bool IsEmpty => _dataArray is null || _dataArray.Length == 0;

    public int Count { get; private set; }

    public void SetValue(int index, decimal? data, string format, ExcelStyleColor color)
    {
        if (data == null)
        {
            return;
        }

        if (_dataArray == null)
        {
            _dataArray = new ExcelDataValue[index + 1];
            Count = 1;
        }
        else
        {
            if (index >= _dataArray.Length)
            {
                var arr = new ExcelDataValue[index + 1];
                Array.Copy(_dataArray, arr, _dataArray.Length);
                _dataArray = arr;
            }

            if (_dataArray[index].IsEmpty)
            {
                Count++;
            }
        }

        _dataArray[index] = new ExcelDataValue((decimal)data, format, color);
    }

    public bool TryGetValue(int index, out ExcelDataValue data)
    {
        data = default;

        if (_dataArray == null || _dataArray.Length <= index)
        {
            return false;
        }

        data = _dataArray[index];
        return !data.IsEmpty;
    }

    public void CopyValue(ExcelData data)
    {
        if (data._dataArray == null)
        {
            return;
        }

        _dataArray = new ExcelDataValue[data._dataArray.Length];
        Array.Copy(data._dataArray, _dataArray, data._dataArray.Length);
    }
}